<template>
  <div class="smart-plan-common-table">
    <div class="smart-plan-common-header mar-b-16">
      <div class="smart-plan-common-header__left">
        <slot name="header_left"></slot>
      </div>
      <div class="smart-plan-common-header__right flex-x">
        <el-input
          v-if="showSearchInput"
          v-model="keyword"
          :placeholder="placeholder"
          @keyup.enter.native="search"
        ></el-input>
        <!-- 选择列 -->
        <div
          v-if="showSelectColumn"
          :class="['select-column', 'task-ai', 'task-font14', 'task-c6', 'task-pointer', ' cur-point', 'mar-l-16']"
          @click="showColumnsSetting"
          v-track="$track.formatParams('SELECT_COLUMN')"
        >
          <span class="task-mr4">{{$t('common.base.choiceCol')}}</span>
          <i class="iconfont icon-fdn-select"></i>
        </div>
      </div>
    </div>
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :class="['common-list-table', 'bbx-normal-list-box']"
      header-row-class-name="common-list-table-header__v2"
      row-class-name="base-table-row-v3"
      :data="listData"
      border
    >
      <template slot="empty">
        <BaseListForNoData
          v-show="!listLoading"
          table-type="smallTable"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>

      <el-table-column
        v-for="column in columns.filter(column => column.show)"
        :key="column.fieldName"
        :label="column.displayName"
        :prop="column.fieldName"
        :show-overflow-tooltip="column.fieldName !== 'customerTag'"
        :width="column.width"
        :min-width="column.minWidth || '120px'">
        <template slot-scope="scope">
          <template v-if="column.fieldName === 'serialNumber'">
            <div
              v-if="createDimension == 0"
              :class="globalIsHaveProductViewDetailAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'"
              @click.stop.prevent="openProductDetailTab(scope.row.id)"
            >
              {{ scope.row[column.fieldName] }}
            </div>
            <div
              v-if="createDimension == 1"
              :class="globalIsHaveCustomerViewDetailAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'"
              @click.stop.prevent="openCustomerDetailTab(scope.row.id || scope.row.uuid)"
            >
              {{ scope.row[column.fieldName] }}
            </div>
          </template>
          <!-- 工单编号、事件编号、PaaS编号、活动名称、计划名称、合同编号 -->
          <template v-else-if="['bizNo', 'activitiesName', 'planName', 'contractNo'].includes(column.fieldName)">
            <div
              v-if="bizType == 'PAAS'"
              class="view-detail-btn"
              @click.stop.prevent="openPassTab(scope.row)"
            >
              {{ scope.row[column.fieldName] }}
            </div>
            <div
              v-else-if="bizType == 'TASK'"
              :class="globalIsHaveTaskViewDetailAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'"
              @click.stop.prevent="openTaskTab(scope.row.taskUUID, scope.row[column.fieldName])"
            >
              {{ scope.row[column.fieldName] }}
            </div>
            <div
              v-else-if="bizType == 'EVENT'"
              :class="globalIsHaveEventViewDetailAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'"
              @click.stop.prevent="
                openEventDetailTab(scope.row.id, scope.row[column.fieldName])
              "
            >
              {{ scope.row[column.fieldName] }}
            </div>
            <div
              v-else-if="bizType == 'ACTIVITY_RESEARCH'"
              class="view-detail-btn"
              @click.stop.prevent="openActivityDetailTab(scope.row.id, scope.row[column.fieldName])"
            >
              {{ scope.row[column.fieldName] }}
            </div>
            <div
              v-else-if="column.fieldName == 'planName'"
              :class="hasViewAuth ? 'view-detail-btn' : 'view-detail-btn-disabled'"
              @click.stop.prevent="openSmartPlanDetailTab(scope.row.id)"
            >
              {{ scope.row[column.fieldName] }}
            </div>
            <div
              v-else-if="column.fieldName == 'contractNo'"
              class="view-detail-btn"
              @click.stop.prevent="openContractDetailTab(scope.row)"
            >
              {{ scope.row[column.fieldName] }}
            </div>
          </template>
          <!-- 工单状态、事件状态 -->
          <template v-else-if="column.fieldName === 'state'">
            <template v-if="bizType == 'TASK'">
              <span v-if="scope.row.attribute && scope.row.attribute.lastPassedNodeStateName">
              {{scope.row.attribute.lastPassedNodeStateName}}
              </span>
              <span v-else>
                {{ scope.row.state && taskStateEnum.getName(scope.row.state) }}
              </span>
            </template>
            <template v-else-if="bizType == 'EVENT'">
              {{ scope.row.state && eventStateEnum.getName(scope.row.state) }}
            </template>
          </template>
          <!-- 活动调研状态 -->
          <template v-else-if="column.fieldName === 'activitiesState'">
            {{ activityStateMap[scope.row[column.fieldName]] }}
          </template>
          <template v-else-if="column.fieldName === 'customer' || column.formType === 'customer'">
            {{ getCustomerName(scope.row, column.fieldName) }}
          </template>
          <template v-else-if="column.formType === 'related_customers'">
            {{ getRelatedCustomerName(scope.row, column.fieldName) }}
          </template>
          <template v-else-if="column.fieldName === 'product' || column.formType === 'product'">
            {{ getProductName(scope.row, column.fieldName) }}
          </template>
          <template v-else-if="column.fieldName === 'customerAddress' || column.formType == 'customerAddress'">
            {{ getCustomerAddressName(scope.row, column.fieldName) }}
          </template>
          <template v-else-if="column.fieldName === 'detailAddress'">
            <pre class="pre-text">{{scope.row.customerAddress && scope.row.customerAddress.adAddress}}</pre>
          </template>
          <template v-else-if="column.fieldName === 'tags'">
            {{(scope.row.tags || scope.row.tagList) | tagName}}
          </template>
          <template v-else-if="['lmName', 'linkman'].includes(column.fieldName) || column.formType == 'linkman'">
            {{ getLinkmanName(scope.row, column.fieldName) }}
          </template>
          <template v-else-if="column.fieldName === 'lmPhone'">
            <span class="align-items-center"> {{ (scope.row.linkman && scope.row.linkman.phone) || scope.row.lmPhone || (scope.row.mainLinkman && scope.row.mainLinkman.phone) }}
              <biz-call-icon :value="scope.row.linkman && scope.row.linkman.phone" :source-data="callCenterSourceData(scope)" />
            </span>
          </template>
          <template v-else-if="column.fieldName === 'lmEmail'">
            {{ getLinkmanEmail(scope.row) }}
          </template>
          <template v-else-if="column.fieldName === 'createUser'">
            <template v-if="isOpenData">
              <open-data type='userName' :openid="scope.row.createUserStaffId"></open-data>
            </template>
            <template v-else>
              {{scope.row.createUserName}}
            </template>
          </template>
          <template v-else-if="['manager', 'customerManagerName', 'customerManager', 'managerPerson'].includes(column.fieldName)">
            {{getCustomerManagerName(scope.row)}}
          </template>
          <template v-else-if="column.fieldName === 'remindCount'">
            {{scope.row.remindCount || 0}}
          </template>
          <template v-else-if="column.formType === 'location'">
            {{ scope.row[column.fieldName] && scope.row[column.fieldName].address}}
          </template>
          <template v-else-if="column.fieldName === 'productCompleteAddress'">
            {{ scope.row[column.fieldName] }}
          </template>
          <template v-else-if="column.formType === 'address'">
            {{formatAddress(scope.row[column.fieldName])}}
          </template>
          <template v-else-if="column.formType === 'connector'">
            <div v-if="scope.row[column.fieldName]" class="view-detail-btn task-client" @click.stop="openConnectorDialog(column, scope.row)">
              {{ $t('common.base.view') }}
            </div>
          </template>
          <div
            class="pre-text"
            v-else-if="column.formType === 'textarea'"
            v-html="buildTextarea(scope.row[column.fieldName])"
            @click="openOutsideLink"></div>

          <template v-else-if="column.formType === 'user'">

            <template v-if="isOpenData">
              <template v-if="Array.isArray(scope.row[column.fieldName])">
                <open-data
                  v-for="item in (scope.row[column.fieldName])"
                  :key="item.staffId"
                  type="userName"
                  :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                <open-data type="userName" :openid="scope.row[column.fieldName] && scope.row[column.fieldName].staffId"></open-data>
              </template>
            </template>

            <template v-else>
              <pre class="pre-text">{{ $formatFormField(column, scope.row) }}</pre>
            </template>
          </template>
          <template v-else-if="column.fieldName === 'customerTag'">
            <el-tooltip placement="top">
              <div slot="content">
                {{ (scope.row.tenantTagList || scope.row.esTenantTagList) | tagName }}
              </div>
              <base-tags :value="customerLabel(scope.row.tenantTagList || scope.row.esTenantTagList)" />
            </el-tooltip>
          </template>
          <template v-else-if="column.fieldName === 'status'">
            {{ getStateText(scope.row.status) }}
          </template>
          <!-- 计划状态 -->
          <template v-else-if="column.fieldName === 'planStatus'">
            {{ getStatusName(scope.row.planStatus) }}
          </template>
          <!-- 任务类型 -->
          <template v-else-if="column.fieldName === 'planType'">
            {{ getModuleTypeName(scope.row.planType) }}
          </template>
          <!-- 创建维度 -->
          <template v-else-if="column.fieldName === 'createDimension'">
            {{ scope.row.createDimension == 1 ? $t('smartPlan.createByCustomerDimension') : $t('smartPlan.createByProductDimension') }}
          </template>
          <!-- 计划开始时间 -->
          <template v-else-if="column.fieldName === 'startSetting'">
            {{ getStartAndEndTimeLabel(scope.row.startSetting, 'start') }}
          </template>
          <!-- 计划结束时间 -->
          <template v-else-if="column.fieldName === 'endSetting'">
            {{ getStartAndEndTimeLabel(scope.row.endSetting, 'end') }}
          </template>
          <!-- 计划重复周期 -->
          <template v-else-if="column.fieldName === 'periodSetting'">
            {{ getPeriodLabel(scope.row.periodSetting) }}
          </template>
          <template v-else-if="column.fieldName === 'productTemplate'">
            {{ scope.row.templateName }}
          </template>
          <!-- 服务商 -->
          <template v-else-if="column.formType == 'serviceProviders'">
            {{ scope.row.serviceProviderSubForm | serviceProviderColumnValue }}
          </template>
          <template v-else-if="column.fieldName === 'createTime'">
            {{ scope.row.createTime | formatDate }}
          </template>
          <!-- 预计创建时间、paas创建时间 -->
          <template v-else-if="['planTime', 'executeTime'].includes(column.fieldName)">
            {{ (scope.row.planJobDetail && scope.row.planJobDetail[column.fieldName]) | formatDate }}
          </template>
          <!-- 失败原因 -->
          <template v-else-if="['errorMsg'].includes(column.fieldName)">
            {{ scope.row.planJobDetail && scope.row.planJobDetail[column.fieldName] }}
          </template>
          <template v-else-if="column.fieldName == 'linkmanName'">
            {{ scope.row.linkman && scope.row.linkman.name }}
          </template>
          <template v-else-if="column.fieldName == 'phone'">
            {{ scope.row.linkman && scope.row.linkman.phone }}
          </template>
          <template v-else-if="['catalogId', 'pathName'].includes(column.fieldName)">
            {{ (scope.row['pathName'] && scope.row['pathName'].replace(new RegExp("/","g") ,' / ')) || scope.row['type'] || '' }}
          </template>
          <template v-else-if="column.fieldName === 'productManager'">
            <template v-if="isOpenData">
              <open-data type='userName' :openid="scope.row.productManagerStaffId"></open-data>
            </template>
            <template v-else>
              {{scope.row.productManagerName}}
            </template>
          </template>
          <template v-else-if="column.fieldName === 'otherAmount'">
            {{ getCurrencyAmountView(scope.row, column.fieldName) }}
          </template>
          <template v-else-if="column.fieldName === 'discountAmount'">
            {{ getCurrencyAmountView(scope.row, column.fieldName) }}
          </template>
          <template v-else-if="column.fieldName === 'contractAmount'">
            {{ getCurrencyAmountView(scope.row, column.fieldName) }}
          </template>
          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
        </template>
      </el-table-column>
      <!-- start 操作 -->
      <el-table-column
        :label="$t('common.base.operation')"
        v-if="operation.isShow"
        :width="operation.width"
        fixed="right"
      >
        <template slot-scope="scope">
          <slot name="actions" :row="scope.row"></slot>
        </template>
      </el-table-column>
      <!-- end 操作 -->
    </el-table>
    <div ref="tableFooterContainer" class="table-footer comment-list-table-footer bbx-normal-table-footer-10">
      <div class="list-info">
        <i18n path="common.base.table.totalPiece">
          <span place="count" class="level-padding">{{ total }}</span>
        </i18n>
      </div>
      <el-pagination
        class="comment-list-table-footer-pagination"
        background
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page-size="page.pageSize"
        :current-page="page.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- start 选择列设置 -->
    <biz-select-column ref="advanced" @save="saveColumnStatus" />
    <!-- end 选择列设置 -->
    <!-- 连接器明细弹窗 -->
    <connector-table-dialog ref="connectorDialogRef" />
  </div>
  
</template>

<script>
/* utils */
import { t } from '@src/locales'
import { fmtDist } from '@src/util/addressUtil';
import { formatAddress, formatDate, isEmpty, isString } from 'pub-bbx-utils';
import { getRootWindowInitData } from '@src/util/window'
import { isOpenData, openAccurateTab } from '@src/util/platform'
import { customerLabel } from '@src/modules/customer/util/customer.js';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import StorageUtil from '@src/util/storage.ts';
import { CURRENCY_SUFFIX } from '@src/util/currency';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage();

/* mixin */
import AuthMixin from '@src/mixins/authMixin'
import ConnectorMixin from '@src/mixins/connectorMixin'
import SmartPlanMixin from '@src/modules/smartPlan/mixin/index.js'
/* service */
import { getFieldName, mergeFieldsWithProperty } from '@service/FieldService.ts';
import { smoothQualityInfoFieldForTable } from '@service/QualityInfoService.ts'
/* enum */
import TaskStateEnum from '@model/enum/TaskStateEnum.ts';
import EventStateEnum from '@model/enum/EventStateEnum.ts';
import StorageModuleEnum from '@model/enum/StorageModuleEnum';

const link_reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;

export default {
  name: 'common-table',
  mixins: [AuthMixin, ConnectorMixin, SmartPlanMixin],
  props: {
    showSearchInput: {
      type: Boolean,
      default: true
    },
    listData: {
      type: Array,
      default: () => ([])
    },
    fields: {
      type: Array,
      default: () => ([])
    },
    listLoading: {
      type: Boolean,
      default: true
    },
    total: {
      type: Number,
      default: 0
    },
    createDimension: {
      type: Number,
      default: 0
    },
    bizType: {
      type: String,
      default: ''
    },
    // 计划范围、任务明细
    type: {
      type: String,
      default: ''
    },
    // 是否显示操作和操作的宽度
    operation: {
      type: Object,
      default: () => ({})
    },
    placeholder: {
      type: String,
      default: t('smartPlan.searchNo')
    },
    storageKey: {
      type: String,
      default: ''
    },
    showSelectColumn: {
      type: Boolean,
      default: false
    },
  },
  filters: {
    formatDate (val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD HH:mm:ss');
    },
    tagName(value) {
      if (!value || !Array.isArray(value) || !value.length) return '';

      return value
        .filter(tag => tag && tag.tagName)
        .map(tag => tag.tagName)
        .join('，');
    },
    // 表格服务商字段解析
    serviceProviderColumnValue(value) {
      if (!value || !Array.isArray(value) || !value.length) return '';

      return value
        .map(item => item.providerName || item.tagName)
        .join('，');
    },
  },
  data() {
    return {
      columns: [],
      keyword: '',
      // 分页
      page: {
        pageNum: 1,
        pageSize: 10
      },
      isOpenData,
      rootWindowInitData: getRootWindowInitData(),
      taskStateEnum: TaskStateEnum,
      eventStateEnum: EventStateEnum,
      activityStateMap: [
        t('common.base.draft'),
        t('common.base.notStart'),
        t('common.base.processing'),
        t('common.customer.questionnaire.expired'),
        t('common.customer.questionnaire.deactivated')
      ],
    }
  },
  computed: {
    auth() {
      return this.rootWindowInitData?.user?.auth || {}
    },
  },
  mounted() {
    this.buildColumns()
  },
  methods: {
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.search();
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getList();
    },
    search() {
      this.page.pageNum = 1
      this.getList()
    },
    getList() {
      this.$nextTick(() => {
        // 滚动至表格顶部
        this.$refs.multipleTable?.$refs?.bodyWrapper?.scrollTo(0, 0)
      })
      const params = {
        ...this.page,
        keyword: this.keyword
      }
      this.$emit('search', params)
    },
    formatAddress,
    // 呼叫中心来源数据
    callCenterSourceData(scope){
      return {
        sourceTypeId: scope.row.id,
        sourceType: 'customer',
      }
    },
    openOutsideLink(e) {
      let url = e.target.getAttribute('url');
      if (!url) return;
      if (!/http/gi.test(url))
        return this.$platform.alert(t('common.base.tip.confirmHttpProtocol'));
      this.$platform.openLink(url);
    },
    buildTextarea(value) {
      let textareaValue = value
        ? value.replace(link_reg, (match) => {
          return `<a href="javascript:;" target="_blank" url="${match}">${match}</a>`
        })
        : '';

      return textareaValue.replace(/\s/g, '&nbsp;');
    },
    customerLabel,
    getStateText(status) {
      if (status == 1) return t('common.base.processing')
      if (status == 2) return t('common.base.usualStatus.finish')
      if (status == 3) return t('common.task.type.offed')
      if (status == 4) return t('common.base.draft')
      if (status == 5) return t('common.task.type.refused')
      return status
    },
    getCustomerName(row, fieldName) {
      const customer = row[fieldName] || row.customer || row.customerEntity || row.customerVO || {}
      if (Array.isArray(customer)) {
        return customer.map(item => item.name).join(',')
      }
      return customer.name || row.cusName
    },
    getRelatedCustomerName(row, fieldName) {
      const customer = row[fieldName] || {}
      if (Array.isArray(customer)) {
        return customer.map(item => item.name).join(',')
      }
      return customer.name
    },
    getLinkmanName(row, fieldName) {
      const linkman = row[fieldName] || row.linkman || row.linkMan || row.mainLinkman || row.linkManVO || {}
      if (Array.isArray(linkman)) {
        return linkman.map(item => item.name).join(',')
      }
      return linkman.name || row.lmName
    },
    getLinkmanEmail(row) {
      return row.lmEmail || row.mainLinkman?.email
    },
    getCustomerManagerName(row) {
      const manager = row.customerManagerName || row.customerManager?.displayName || row.manager
      if (Array.isArray(manager)) {
        return manager.map(item => item.displayName).join(',')
      }
      return manager
    },
    getProductName(row, fieldName) {
      let product = row[fieldName] || {}
      if (Array.isArray(row.products)) {
        product = row.products
      } else if ((row.product && row.product.id) || Array.isArray(row.product)) {
        product = row.product
      }
      if (Array.isArray(product)) {
        return product.map(item => item.name || item[`${fieldName}_name`]).filter(Boolean).join(',')
      }
      return product.name
    },
    getCustomerAddressName(row, fieldName) {
      const address = row[fieldName] || row.customerAddress || row.cusAddress || row.address || row.mainAddress
      if (Array.isArray(address)) {
        return address.map(item => this.formatAddress(item)).join(',')
      }
      if (isString(address)) return address
      return this.formatAddress(address)
    },
    // 获取币种数据
    getCurrencyAmountView(row, fieldName) {
      const currency = row[fieldName + CURRENCY_SUFFIX] || 'CNY'
      return internationalGray ? `${row[fieldName]} ${currency}` : row[fieldName]
    },
    // 打开产品详情tab
    openProductDetailTab (productId) {
      if (!this.globalIsHaveProductViewDetailAuth) return

      let fromId = window.frameElement.getAttribute('id')
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductView,
        key: productId,
        params: 'noHistory=1',
        fromId
      })
    },
    // 打开客户详情tab
    openCustomerDetailTab(customerId) {
      if (!this.globalIsHaveCustomerViewDetailAuth) return

      let fromId = window.frameElement.getAttribute('id')
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
        fromId
      })
    },
    /**
     * @description 打开选择列设置
     */
    showColumnsSetting() {
      this.$refs.advanced.open(this.columns);
    },
    /**
     * @description 构建 列表 + 选择列
     */
    async buildColumns() {
      const localStorageData = await this.getIndexedDbData();

      let columnStatus = []
      const storageKey = this.storageKey;
      if(storageKey && localStorageData[storageKey]){
        columnStatus = localStorageData[storageKey]
      }else{
        columnStatus = localStorageData.columnStatus && localStorageData.columnStatus
      }

      if(!columnStatus) columnStatus = []

      let localColumns = columnStatus
        .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          }
          return acc
        }, {});
      let fields = this.fields

      if(fields.some(item => item.formType === 'relationForm')){
        // 过滤掉关联表单的相关内容
        fields = fields.filter(val => val.formType !== 'relationForm')
      }

      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns)
      }

      fields = smoothQualityInfoFieldForTable(fields).filter(Boolean)

      let columns = fields
        .filter(f => !['attachment', 'separator', 'info', 'autograph'].includes(f?.formType))
        .map((field) => {
          let minWidth = 120;

          if (['address'].indexOf(field.formType) >= 0) {
            minWidth = 200;
          }

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (
            field.formType === 'datetime'
            || field.fieldName === 'updateTime'
            || field.fieldName === 'createTime'
          ) {
            minWidth = 160;
          }

          if (
            ['taddress', 'templateName'].indexOf(field.fieldName) >= 0
          ) {
            minWidth = 200;
          }

          if (field.fieldName === 'bizNo') {
            field.width = 216
          }
          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            isSystem: field.isSystem,
            fixed: field.fixed
          };
        })
        .map((col) => {
          let show = col.show === true;
          let { width } = col;
          let localField = localColumns[col.field]?.field || null;
          let fixLeft = localField?.fixLeft || null;

          if (null != localField) {
            if (localField.width) {
              width = typeof localField.width == 'number'
                ? `${localField.width}px`
                : localField.width;
            }
            show = localField.show !== false;
          } else {
            show = true;
          }
          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left'

          return col;
        });

      // 并本地缓存列数据至当前实例的列数据
      this.mergeLocalStorageColumnsToColumns(columns)

      this.columns = []
      this.$nextTick(() => {
        this.columns = columns;
      })
      return columns
    },
    async getIndexedDbData() {
      let data = {}
      try {
        data = await StorageUtil.storageGet(this.storageKey, {}, StorageModuleEnum.SmartPlan)
      } catch (error) {
        data = {}
        console.error('Caused ~ planTaskList ~ getIndexedDbData ~ error', error)
      }
      
      return data
    },
    /**
     * @description 合并本地缓存列数据至当前实例的列数据
     */
    async mergeLocalStorageColumnsToColumns(columns = []) {
      const { columnStatus } = await this.getIndexedDbData()
      if (isEmpty(columnStatus)) return

      mergeFieldsWithProperty(
        columns,
        columnStatus,
        (column, localStorageDataColumnItem) => {
          // 列名不匹配则返回
          if (getFieldName(column) !== getFieldName(localStorageDataColumnItem)) return
          // 覆盖列显示状态
          column.show = Boolean(localStorageDataColumnItem.show)
          // 覆盖宽度数据
          if (localStorageDataColumnItem?.width) {
            column.width = localStorageDataColumnItem.width
          }
        }
      )
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = []

      originFields.forEach(originField => {
        let {
          fieldName
        } = originField
        let field = fieldsMap[fieldName]

        if (field) {
          let {
            index
          } = field
          fields[index] = originField
        } else {
          unsortedFields.push(originField)
        }

      })

      return fields.concat(unsortedFields)
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || []
      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage()
      })
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    async saveColumnStatusToStorage() {
      const localStorageData = await this.getIndexedDbData();
      let columnsStatus = null

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      const saveKey = this.storageKey

      if(localStorageData[saveKey]){
        try{
          localStorageData[saveKey] = columnsList;
          columnsStatus = localStorageData[saveKey];
        }catch(err){
          console.error(err)
        }
      }else if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }
      if(saveKey){
        this.saveDataToIndexedDb(saveKey, columnsStatus)
      }else{
        this.saveDataToIndexedDb('columnStatus', columnsStatus); // 默认选择列保存
      }
    },
    /**
     * @description 保存数据到本地indexedDB
    */
    async saveDataToIndexedDb(key, value) {
      const data = await this.getIndexedDbData()
      data[key] = value
      StorageUtil.storageSet(this.storageKey, data, StorageModuleEnum.SmartPlan)
    },
  },
}
</script>

<style lang="scss">
.smart-plan-common-table {
  padding: 0 16px;
  background: #fff;
  .smart-plan-common-header {
    display: flex;
    justify-content: space-between;
  }
  .select-column {
    display: flex;
    align-items: center;
    min-width: 64px;
  }
  .table-footer .list-info {
    @include text-ellipsis()
  }
}
</style>